package com.hxz.djbxkj.HxzExecutor.ExecutorComponent;

import com.hxz.djbxkj.HxzExecutor.ExecutorComponent.Imp.CreateExecutorJk;
import com.hxz.djbxkj.HxzExecutor.ExecutorComponent.Imp.RunJk;
import com.hxz.djbxkj.HxzExecutor.Model.InitExcutorMode;
import com.hxz.djbxkj.HxzExecutor.Model.TaskMode;

import javax.annotation.PreDestroy;
import java.util.concurrent.ThreadPoolExecutor;

public class ExecutorComponent implements CreateExecutorJk {
    private static ThreadPoolExecutor tp;
    private RunJk rj;

    public ExecutorComponent(InitExcutorMode initExcutorMode, RunJk rj){
        if(null==tp) tp=CreateExecutor(initExcutorMode);
        this.rj=rj;
    }

    public static ThreadPoolExecutor getThreadPoolExecutor(){
        return tp;
    }


    public TaskMode doPlay(TaskMode tm){
        return rj.doPlay(tm);
    }


    public void shutdown(){
        if(null!=tp) tp.shutdown();
        tp=null;
    }


    /**
     * 默认创建方式
     * @param initExcutorMode
     * @return
     */
    @Override
    public ThreadPoolExecutor CreateExecutor(InitExcutorMode initExcutorMode) {//建议使用无边界队列，有边界队列容易出现队列溢出现象(很容易抛异常)
        if(null==initExcutorMode.getHandler()){
            return new ThreadPoolExecutor(initExcutorMode.getCorePoolSize(),initExcutorMode.getMaximumPoolSize(),initExcutorMode.getKeepAliveTime(),initExcutorMode.getUnit(),initExcutorMode.getWorkQueue());
        }else{
            return new ThreadPoolExecutor(initExcutorMode.getCorePoolSize(),initExcutorMode.getMaximumPoolSize(),initExcutorMode.getKeepAliveTime(),initExcutorMode.getUnit(),initExcutorMode.getWorkQueue(),initExcutorMode.getHandler());
        }
    }


    /**
     * 销毁线程池
     */
    @PreDestroy
    public final void destroy() {
        tp.shutdown();
    }

}
